package com.osell.selection.ui.product;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.transition.TransitionManager;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.github.lzyzsd.circleprogress.DonutProgress;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.data.network.entity.ProductDetail;
import com.osell.selection.ui.base.BaseActivity;
import com.osell.selection.ui.base.SimpleFragmentPagerAdapter;
import com.osell.selection.ui.common.WebViewActivity;
import com.osell.selection.util.DimenUtils;
import com.osell.selection.util.Spans;
import com.osell.selection.widget.BadgeView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import fr.castorflex.android.verticalviewpager.VerticalViewPager;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

public class ProductDetailActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.fl_product_content)
    FrameLayout fl_product_content;
    @BindView(R.id.btn_back)
    ImageButton btn_back;
    @BindView(R.id.tv_silk_balance)
    TextView tv_silk_balance;
    @BindView(R.id.tv_rate_balance)
    TextView tv_rate_balance;
    @BindView(R.id.vp_product_detail)
    VerticalViewPager vp_product_detail;
    @BindView(R.id.tv_go_to_comment)
    TextView tv_go_to_comment;
    @BindView(R.id.tv_go_to_consult)
    TextView tv_go_to_consult;
    @BindView(R.id.tv_go_to_share)
    TextView tv_go_to_share;

    @BindView(R.id.fl_countdown)
    FrameLayout fl_count_down;
    @BindView(R.id.dp_countdown)
    DonutProgress dp_countdown;
    @BindView(R.id.tv_countdown)
    TextView tv_countdown;

    private BadgeView mBadgeConsult;
    private BadgeView mBadgeShare;

    private ProductDetail mProductDetail;
    private CompositeDisposable mDisposables;

    private int time;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);

        mBadgeConsult = new BadgeView(this, tv_go_to_consult);
        mBadgeShare = new BadgeView(this, tv_go_to_share);
        mBadgeConsult.setBadgeMargin(0);
        mBadgeShare.setBadgeMargin(0);
        mBadgeConsult.setTextSize(10);
        mBadgeShare.setTextSize(10);

        btn_back.setOnClickListener(this);
        tv_go_to_comment.setOnClickListener(this);
        tv_go_to_consult.setOnClickListener(this);
        tv_go_to_share.setOnClickListener(this);
        dp_countdown.setShowText(false);

        mDisposables = new CompositeDisposable();
        setupContent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDisposables.dispose();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                onBackPressed();
                break;
            case R.id.tv_go_to_comment:
                if (mProductDetail != null) {
                    RateFragment.newInstance(mProductDetail.id, mProductDetail.number).show(getSupportFragmentManager(), "RateFragment");
                }
                break;
            case R.id.tv_go_to_consult:
                if (mProductDetail != null) {
                    v.getContext().startActivity(new Intent(v.getContext(), WebViewActivity.class)
                            .putExtra("url", mProductDetail.chatLink));
                }
                break;
            case R.id.tv_go_to_share:
                if (mProductDetail != null) {
                    v.getContext().startActivity(new Intent(v.getContext(), WebViewActivity.class)
                            .putExtra("url", mProductDetail.shareLink));
                }
                break;
            default:
                break;
        }
    }

    private void countdown() {
        fl_count_down.setVisibility(View.VISIBLE);
        mDisposables.add(Observable.intervalRange(1, 15, 1, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    long countdown = 15 - aLong;
                    tv_countdown.setText(new Spans()
                            .append(String.valueOf(++time),
                                    new ForegroundColorSpan(ContextCompat.getColor(tv_countdown.getContext(), R.color.colorPrimary)),
                                    new AbsoluteSizeSpan((int) DimenUtils.dipToPixels(22, tv_countdown.getContext())),
                                    new StyleSpan(Typeface.BOLD))
                            .append(System.getProperty("line.separator"))
                            .append(getString(R.string.second)));
                    dp_countdown.setProgress(aLong);
                    if (countdown == 0) {
                        mDisposables.add(Observable.just(true)
                                .delay(1, TimeUnit.SECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aBoolean -> {
                                    if (time == 60) {
                                        fl_count_down.setVisibility(View.GONE);
                                    } else {
                                        dp_countdown.setProgress(0);
                                        tv_countdown.setText(new Spans()
                                                .append(getString(R.string.end),
                                                        new ForegroundColorSpan(ContextCompat.getColor(tv_countdown.getContext(), R.color.colorTextLightGray)),
                                                        new AbsoluteSizeSpan((int) DimenUtils.dipToPixels(22, tv_countdown.getContext())),
                                                        new StyleSpan(Typeface.BOLD)));
                                        countdown();
                                    }
                                    addReward();
                                }, throwable -> {
                                }));
                    }
                }, throwable -> {

                }));
    }

    private void addReward() {
        mDisposables.add(RestAPI.getInstance().oSellService()
                .addReward(
                        mUserInfoSp.getString("user_id", ""),
                        mUserInfoSp.getString("user_key", ""),
                        mProductDetail.id,
                        mProductDetail.number)
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(rewardResponseData -> {
                    if (TextUtils.equals("000000", rewardResponseData.code)) {
                        tv_silk_balance.setText(new Spans()
                                .append(rewardResponseData.data.silkBalance,
                                        new ForegroundColorSpan(ContextCompat.getColor(ProductDetailActivity.this, R.color.colorTextBlack)),
                                        new StyleSpan(Typeface.BOLD))
                                .append(" ")
                                .append(getString(R.string.silk)));
                        String s = "(" + rewardResponseData.data.silkDollarBalance + ")";
                        tv_rate_balance.setText(s);
                    } else {
                        Toast.makeText(MyApplication.getInstance(), rewardResponseData.message, Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> Toast.makeText(MyApplication.getInstance(), throwable.getMessage(), Toast.LENGTH_SHORT).show()));
    }

    private void setupContent() {
        mDisposables.add(RestAPI.getInstance().oSellService()
                .getProductDetail(getIntent().getStringExtra("product_number"),
                        mUserInfoSp.getString("user_id", ""),
                        mUserInfoSp.getString("user_key", ""))
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productDetailResponseData -> {

                    mProductDetail = productDetailResponseData.data;

                    TransitionManager.beginDelayedTransition(fl_product_content);
                    tv_silk_balance.setText(new Spans()
                            .append(mProductDetail.silkBalance,
                                    new ForegroundColorSpan(ContextCompat.getColor(ProductDetailActivity.this, R.color.colorTextBlack)),
                                    new StyleSpan(Typeface.BOLD))
                            .append(" ")
                            .append(getString(R.string.silk)));
                    String s = "(" + mProductDetail.silkDollarBalance + ")";
                    tv_rate_balance.setText(s);
                    mBadgeShare.setText(mProductDetail.share);
                    mBadgeConsult.setText(mProductDetail.consult);
                    mBadgeShare.show();
                    mBadgeConsult.show();

                    vp_product_detail.setAdapter(new SimpleFragmentPagerAdapter(getSupportFragmentManager())
                            .addFragment(ProductHeadFragment.newInstance(mProductDetail), null)
                            .addFragment(ProductFootFragment.newInstance(mProductDetail), null));

                    if (TextUtils.equals("no", mProductDetail.silkGained)) {
                        countdown();
                    }
                }, throwable -> {
                }));
    }
}
